using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using ElectronicMallProject.Backend.Api.Database;
using ElectronicMallProject.Backend.Api.Repository;
using Microsoft.IdentityModel.Tokens;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using ElectronicMallProject.Backend.Api.Params;
using System.Text;
using ElectronicMallProject.Backend.Api.Filters;
using Microsoft.Extensions.FileProviders;

namespace ElectronicMallProject.Backend.Api
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        //添加跨域访问变量
        readonly string _allowCors = "AllowSpecificOrigins";

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy(_allowCors,
                builder => builder.AllowAnyHeader()
                .AllowAnyMethod()
                .AllowAnyOrigin());
            });

            services.AddControllers();

            // 注入 IRepository接口及其实现类
            services.AddScoped(typeof(IRepository<>), typeof(EfRepository<>));

            //注入数据库上下文
            services.AddDbContext<DbInit>();

            //配置token验证信息
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(option =>
        {
            option.RequireHttpsMetadata = false;
            option.SaveToken = true;

            var token = Configuration.GetSection("TokenParameter").Get<TokenParameter>();

            option.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(token.Secret)),
                ValidIssuer = token.Issuer,
                ValidateIssuer = true,
                ValidateAudience = false,
            };
        });

            //审计日志储存
            services.AddControllers(options =>
            {
                options.Filters.Add(typeof(AuditLogActionFilter));
            });

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            //静态文件处理
            var staticfile = new StaticFileOptions();

            staticfile.FileProvider = new PhysicalFileProvider(env.ContentRootPath + "/files");

            app.UseStaticFiles(staticfile);

            //路由
            app.UseRouting();


            //注册验证token中间件
            app.UseAuthorization();
            app.UseAuthentication();

            //跨域
            app.UseCors(_allowCors);

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}
